package cn.edu.ustc.brainor.ustcgate;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.text.Html;
import android.widget.TextView;
import android.widget.Toast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 欧伟科 on 2016/10/12.
 * BroadcastReceiver只是用来打开服务, 具体的操作要在服务中完成.
 */

public class OpenServiceBroadcastReceiver extends BroadcastReceiver {
    private ConnectivityManager mConnectivityManager;
    private NetworkInfo netInfo;

    @Override
    public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context, LocationService.class));//只要这句话就行了
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {

            mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            netInfo = mConnectivityManager.getActiveNetworkInfo();
//            locationReceiver(context, intent);
            usteGateReceiver(context, intent);

        }
    }


    private void locationReceiver(Context context, Intent intent) {
        String name = (netInfo != null && netInfo.isAvailable()) ? netInfo.getTypeName() : "NULL";//MOBILE, WIFI, 或者NULL

        //服务
        Intent locationServiceIntent = new Intent(context, LocationService.class);
        locationServiceIntent.putExtra(context.getPackageName() + ".ConnectStat", name);
        context.startService(locationServiceIntent);
    }

    private void usteGateReceiver(final Context context, Intent intent) {

        if (netInfo != null && netInfo.isAvailable()) {
            String name = netInfo.getTypeName();
            if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {

//                Toast.makeText(context, "WIFI", Toast.LENGTH_SHORT).show();
                if (true) {//有WiFi情况下判断是否连上中科大网络
                    new AsyncTask<String, Void, String>() {
                        @Override
                        protected String doInBackground(String... webHTMLs) {
                            return new NetworkConnect().连接网络通();
                        }

                        @Override
                        protected void onPostExecute(String htmlText) {
                            Matcher matcher = Pattern.compile("(?<=信息：)[\\s\\S]+?(?=</td>)").matcher(htmlText);
                            if (matcher.find()) {
                                String 信息 = matcher.group();
                                Toast.makeText(context, 信息.replaceAll("<[\\s\\S]+?>", ""), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }.execute();
                }
            }
        }
    }
}
